/**
 * axios全局配置，包括验证校验及错误处理
 */
import axios from 'axios'
import store from '../store'
import qs from 'qs'
import { sign } from '../util/sign'
import Router from '../router'
// import { Message } from 'element-ui'

// 超时设置
const service = axios.create({
  withCredentials: true,
  timeout: 60000 // 请求超时时间 60s
})

// request 拦截器
service.interceptors.request.use(
  config => {
    const PCToken = store.state.user.PCToken
    if (PCToken) {
      config.data.token = PCToken
    }
    config.data = qs.parse(config.data)
    let data = sign(config.data)
    config.data = JSON.stringify(data)
    config.headers = {
      // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
      'Content-Type': 'application/json'
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    if (Number(response.data.responseCode) === 1008 || Number(response.data.responseCode) === 1004) {
      store.commit('user/setPCToken', '')
      store.commit('user/setName', '')
      store.commit('user/setStatus', '')
      let isAuth = Router.currentRoute.meta.auth
      if (isAuth) {
        window.location.reload()
      }
    }
    return response.data
  },
  err => {
    return Promise.reject(err)
  }
)

export default service
